<template>
  <div class="dashboard-stats">
    <!-- 统计卡片组 -->
    <div class="stats-grid">
      <!-- 新增客户卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-user card-icon"></i>
          <span class="card-title">今日新增客户</span>
          <span class="card-unit">人</span>
        </div>
        <div class="card-value">{{ today.newCustomer || 0 }}</div>
        <div class="card-trend" :class="getTrendClass(today.customerTrend)"> 昨日{{ yesterday.newCustomer || 0 }} 较昨日{{ formatTrend(today.customerTrend || 0) }} </div>
      </el-card>

      <!-- 新增线索卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-sdata card-icon"></i>
          <span class="card-title">今日新增线索</span>
          <span class="card-unit">个</span>
        </div>
        <div class="card-value">{{ today.newClue || 0 }}</div>
        <div class="card-trend" :class="getTrendClass(today.clueTrend)"> 昨日{{ yesterday.newClue || 0 }} 较昨日{{ formatTrend(today.clueTrend || 0) }} </div>
      </el-card>

      <!-- 新增合同卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-file-contract card-icon"></i>
          <span class="card-title">今日新增合同</span>
          <span class="card-unit">个</span>
        </div>
        <div class="card-value">{{ today.newContract || 0 }}</div>
        <div class="card-trend" :class="getTrendClass(today.contractTrend)"> 昨日{{ yesterday.newContract || 0 }} 较昨日{{ formatTrend(today.contractTrend || 0) }} </div>
      </el-card>

      <!-- 新增联系人卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-users card-icon"></i>
          <span class="card-title">今日新增联系人</span>
          <span class="card-unit">人</span>
        </div>
        <div class="card-value">{{ today.newContact || 0 }}</div>
        <div class="card-trend" :class="getTrendClass(today.contactTrend)"> 昨日{{ yesterday.newContact || 0 }} 较昨日{{ formatTrend(today.contactTrend || 0) }} </div>
      </el-card>

      <!-- 当日合同审核卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-document-checked card-icon"></i>
          <span class="card-title">当日合同审核</span>
          <span class="card-unit">个</span>
        </div>
        <!-- 优先显示合同审核统计，如果没有则显示首页统计中的审核数据 -->
        <div class="card-value">{{ contractStats.todayTotalApprovalCount || today.todayTotalApprovalCount || 0 }}</div>
        <div class="card-trend"> 已通过: {{ contractStats.todayApprovedCount || today.todayApprovedCount || 0 }} </div>
      </el-card>

      <!-- 合同金额卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-money card-icon"></i>
          <span class="card-title">今日合同金额</span>
          <span class="card-unit">元</span>
        </div>
        <div class="card-value">{{ formatMoney(today.contractAmount) }}</div>
        <div class="card-trend" :class="getTrendClass(today.amountTrend)"> 昨日{{ formatMoney(yesterday.contractAmount) }} 较昨日{{ formatTrend(today.amountTrend || 0) }} </div>
      </el-card>

      <!-- 回款金额卡片 -->
      <el-card class="stats-card" shadow="hover">
        <div class="card-header">
          <i class="el-icon-wallet card-icon"></i>
          <span class="card-title">今日回款金额</span>
          <span class="card-unit">元</span>
        </div>
        <div class="card-value">{{ formatMoney(today.receivedAmount) }}</div>
        <div class="card-trend" :class="getTrendClass(today.receivedTrend)">
          昨日{{ formatMoney(yesterday.receivedAmount) }} 较昨日{{ formatTrend(today.receivedTrend || 0) }}
        </div>
      </el-card>
    </div>

    <!-- 数据来源提示 -->
    <div class="data-source-tip" v-if="hasRealData">
      <el-tag type="success">正在使用真实数据</el-tag>
    </div>
    <div class="data-source-tip" v-else>
      <el-tag type="warning">正在使用模拟数据</el-tag>
    </div>

    <!-- 刷新提示 -->
    <div class="refresh-tip">
      数据每5分钟自动刷新，上次刷新时间：{{ lastRefreshTime }}
      <el-button type="text" @click="refreshStats" style="margin-left: 10px">立即刷新</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
// 正确导入API - 选择其中一种方式
import DashboardApi from '@/api/modules/dashboard'
import ContractApi from '@/api/modules/contract'

// 格式化金额（分转元，保留2位小数）
const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return (amount / 1).toFixed(2) // 如果后端返回的是元，就不需要除以100
}

// 格式化趋势（添加正负号）
const formatTrend = (trend) => {
  return trend > 0 ? `+${trend}%` : `${trend}%`
}

// 获取趋势样式类
const getTrendClass = (trend) => {
  if (trend > 0) return 'trend-up'
  if (trend < 0) return 'trend-down'
  return 'trend-none'
}

// 今日数据
const today = ref({
  newCustomer: 0,
  newClue: 0,
  newContract: 0,
  newContact: 0,
  contractAmount: 0,
  receivedAmount: 0,
  customerTrend: 0,
  clueTrend: 0,
  contractTrend: 0,
  contactTrend: 0,
  amountTrend: 0,
  receivedTrend: 0,
  todayTotalApprovalCount: 0,
  todayApprovedCount: 0
})

// 合同审核统计
const contractStats = ref({
  todayTotalApprovalCount: 0,
  todayApprovedCount: 0,
  todayRejectedCount: 0,
  todayInitiatedCount: 0
})

// 昨日数据
const yesterday = ref({
  newCustomer: 0,
  newClue: 0,
  newContract: 0,
  newContact: 0,
  contractAmount: 0,
  receivedAmount: 0
})

// 上次刷新时间
const lastRefreshTime = ref('')

// 定时器
let refreshTimer = null
let hasRealData = ref(false) // 标记是否已获取到真实数据

// 加载首页统计数据
const loadHomeStats = async () => {
  try {
    console.log('开始加载首页统计数据...')
    const res = await DashboardApi.getHomeStats()
    console.log('首页统计接口返回:', res)

    // 修复：后端返回 code=0 表示成功，不是 200
    if (res && res.code === 0 && res.data) {
      // 确保数据结构正确
      if (res.data.today) {
        today.value = { ...today.value, ...res.data.today }
      }
      if (res.data.yesterday) {
        yesterday.value = { ...yesterday.value, ...res.data.yesterday }
      }
      lastRefreshTime.value = new Date().toLocaleString()
      hasRealData.value = true
      console.log('首页统计数据加载成功，使用真实数据')
      return true // 返回成功标志
    } else {
      console.warn('首页统计接口返回数据格式异常:', res)
      return false
    }
  } catch (error) {
    console.error('首页统计数据加载失败:', error)
    return false
  }
}

// 加载合同审核统计
const loadContractStats = async () => {
  try {
    console.log('开始加载合同审核统计...')
    const res = await ContractApi.getContractStats()
    console.log('合同审核统计返回:', res)

    // 修复：后端返回 code=0 表示成功
    if (res && res.code === 0 && res.data) {
      contractStats.value = res.data
      console.log('合同审核统计数据加载成功')
      return true
    } else {
      console.warn('合同审核统计接口返回数据格式异常:', res)
      return false
    }
  } catch (error) {
    console.error('合同审核统计加载失败:', error)
    return false
  }
}

// 使用模拟数据（降级方案）
const useMockData = () => {
  console.log('使用模拟数据...')
  today.value = {
    newCustomer: 12,
    newClue: 8,
    newContract: 5,
    newContact: 15,
    contractAmount: 125000,
    receivedAmount: 80000,
    customerTrend: 5,
    clueTrend: -2,
    contractTrend: 10,
    contactTrend: 3,
    amountTrend: 15,
    receivedTrend: 8
  }

  yesterday.value = {
    newCustomer: 10,
    newClue: 10,
    newContract: 4,
    newContact: 12,
    contractAmount: 100000,
    receivedAmount: 70000
  }

  contractStats.value = {
    todayTotalApprovalCount: 8,
    todayApprovedCount: 6,
    todayRejectedCount: 2,
    todayInitiatedCount: 3
  }

  lastRefreshTime.value = new Date().toLocaleString()
  ElMessage.info('使用模拟数据显示')
}

// 加载所有统计数据
const loadStats = async () => {
  console.log('开始加载所有统计数据...')
  const homeStatsSuccess = await loadHomeStats()
  const contractStatsSuccess = await loadContractStats()

  // 如果两个接口都失败了，才使用模拟数据
  if (!homeStatsSuccess && !contractStatsSuccess && !hasRealData.value) {
    console.log('所有接口都失败，使用模拟数据')
    useMockData()
  } else {
    console.log('至少有一个接口成功，使用真实数据')
  }
}

// 立即刷新
const refreshStats = async () => {
  ElMessage.info('正在刷新数据...')
  await loadStats()
  ElMessage.success('数据刷新完成')
}

// 初始化加载+定时刷新
onMounted(() => {
  // 直接加载真实数据
  loadStats()

  // 5分钟刷新一次
  refreshTimer = setInterval(loadStats, 300000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.dashboard-stats {
  padding: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stats-card {
  display: flex;
  height: 160px;
  padding: 16px;
  transition: all 0.3s ease;
  flex-direction: column;
  justify-content: space-between;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  font-size: 14px;
  color: #666;
  align-items: center;
  justify-content: space-between;
}

.card-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #1989fa;
}

.card-unit {
  font-size: 12px;
  color: #999;
}

.card-value {
  margin: 10px 0;
  font-size: 36px;
  font-weight: 700;
  line-height: 1;
  color: #1989fa;
  text-align: center;
}

.card-trend {
  display: flex;
  font-size: 12px;
  align-items: center;
  justify-content: center;
}

.trend-up {
  color: #10b981;
}

.trend-down {
  color: #ef4444;
}

.trend-none {
  color: #9ca3af;
}

.refresh-tip {
  display: flex;
  font-size: 12px;
  color: #999;
  text-align: right;
  align-items: center;
  justify-content: flex-end;
}
</style>
